package Util.Map;

import java.io.Serial;
import java.io.Serializable;
import java.util.*;

public abstract class AbstractMap<K, V> implements Map<K, V> {
    protected AbstractMap(){}

    @Override
    public int size() {
        return entrySet().size();
    }

    @Override
    public boolean isEmpty() {
        return size() == 0;
    }

    @Override
    public boolean containsKey(Object key) {
        Iterator<Entry<K, V>> i = entrySet().iterator();
        if (key == null) {
            while (i.hasNext()) {
                if(i.next().getKey() == null) {return true;}
            }
        }else{
            while (i.hasNext()) {
                if(key.equals(i.next().getKey())) {return true;}
            }
        }
        return false;
    }

    @Override
    public boolean containsValue(Object value) {
        Iterator<Entry<K, V>> i = entrySet().iterator();
        if (value == null) {
            while (i.hasNext()) {
                if(i.next().getValue() == null) {return true;}
            }
        }else{
            while (i.hasNext()) {
                if(value.equals(i.next().getValue())) {return true;}
            }
        }
        return false;
    }

    @Override
    public V get(Object key) {
        Iterator<Entry<K, V>> i = entrySet().iterator();
        if (key == null) {
            while (i.hasNext()) {
                Map.Entry<K,V> e = i.next();
                if(e.getKey() == null) {return e.getValue();}
            }
        }else{
            while (i.hasNext()) {
                Map.Entry<K,V> e = i.next();
                if(key.equals(e.getKey())) {return e.getValue();}
            }
        }
        return null;
    }

    @Override
    //此实现始终抛出UnsupportedOperationException
    public V put(K key, V value) {
        throw new UnsupportedOperationException();
    }

    @Override
    public V remove(Object key) {
        Iterator<Entry<K,V>> i = entrySet().iterator();
        V oldValue = null;
        if (key == null) {
            while (i.hasNext()) {
                Map.Entry<K,V> e = i.next();
                if(e.getKey() == null) {
                    oldValue = e.getValue();
                    i.remove();
                    return oldValue;
                }
            }
        }else{
            while (i.hasNext()) {
                Map.Entry<K,V> e = i.next();
                if(key.equals(e.getKey())) {
                    oldValue = e.getValue();
                    i.remove();
                    return oldValue;
                }
            }
        }
        return null;
    }

    @Override
    public void putAll(Map<? extends K, ? extends V> m) {
        for (Entry<? extends K, ? extends V> e : m.entrySet()) {
            put(e.getKey(), e.getValue());
        }
    }

    @Override
    public void clear() {entrySet().clear();}

    // transient表明该数据不参与序列化, 不是对象持久化的一部分, 该变量内容在序列化后无法被访问, 即只能访问一次
    transient Set<K>        keySet;
    transient Collection<V> values;

    @Override
    public Set<K> keySet() {
        Set<K> ks = keySet;
        if (ks == null) {
            ks = new AbstractSet<K>() {
                @Override
                public Iterator<K> iterator() {
                    return new Iterator<K>() {
                        private Iterator<Map.Entry<K,V>> i = entrySet().iterator();
                        @Override
                        public boolean hasNext() {return i.hasNext();}
                        @Override
                        public K next() {return i.next().getKey();}
                        @Override
                        public void remove() {
                            i.remove();
                        }
                    };
                }

                @Override
                public int size() {return AbstractMap.this.size();}
                @Override
                public boolean isEmpty() {
                    return AbstractMap.this.isEmpty();
                }
                @Override
                public void clear() {
                    AbstractMap.this.clear();
                }
                @Override
                public boolean contains(Object k) {
                    return AbstractMap.this.containsKey(k);
                }
            };
        }
        return ks;
    }

    @Override
    public Collection<V> values() {
        Collection<V> vals= values;
        if (vals == null) {
            vals = new AbstractCollection<V>() {
                @Override
                public Iterator<V> iterator() {
                    return new Iterator<V>() {
                        private Iterator<Map.Entry<K,V>> i = entrySet().iterator();
                        @Override
                        public boolean hasNext() {return i.hasNext();}
                        @Override
                        public V next() {return i.next().getValue();}
                        @Override
                        public void remove() {i.remove();}
                    };
                }

                @Override
                public int size() {return AbstractMap.this.size();}
                @Override
                public boolean isEmpty() {
                    return AbstractMap.this.isEmpty();
                }
                @Override
                public void clear() {
                    AbstractMap.this.clear();
                }
                @Override
                public boolean contains(Object k) {
                    return AbstractMap.this.containsKey(k);
                }
            };
        }
        return null;
    }

    @Override
    public abstract Set<Entry<K, V>> entrySet();

    @Override
    //返回此 AbstractMap 实例的浅拷贝：不会克隆键和值本身
    protected Object clone() throws CloneNotSupportedException {
        AbstractMap<?,?> result = (AbstractMap<?,?>) super.clone();
        result.keySet = null;
        result.values = null;
        return result;
    }

    @Override
    public boolean equals(Object o) {
        if(o == this){
            return true;
        }
        if (!(o instanceof Map<?, ?> m) || m.size() != size()) {
            return false;
        }

        // 原方法中这里被try-catch环绕
        for (Map.Entry<K, V> entry : entrySet()) {
            K key = entry.getKey();
            V value = entry.getValue();
            if(value == null){
                if(!(m.containsKey(key) && m.get(key) == null)){
                    return false;
                }
            }else{
                if (!value.equals(m.get(key))) {
                    return false;
                }
            }
        }

        return true;

    }

    /**
     * Util.Map（映射） 存储键值关联
     * （整体）映射的 hashcode就是entrySet()中每个 K-V 映射的hashcode的总和, 保证相同的Map的hashcode一定相同
      */
    @Override
    public int hashCode(){
        int h = 0;
        for (Map.Entry<K, V> entry : entrySet()) {
            h += entry.hashCode();
        }
        return h;
    }

    @Override
    public String toString(){
        Iterator<Entry<K, V>> i =entrySet().iterator();
        if(!i.hasNext()) {return "{}";}
        StringBuilder sb = new StringBuilder();
        sb.append('{');
        while(true){
            Entry<K, V> entry = i.next();
            K key = entry.getKey();
            V value = entry.getValue();
            sb.append(key).append('=').append(value);
            if(!i.hasNext()){
                return sb.append('}').toString();
            }
            sb.append(',').append(' ');
        }

    }


    /**
     * 此Entry一经初始化, K不允许修改, V允许修改
     * 此类的实例不与任何Map的Entry-Set相关联
     */
    public static class SimpleEntry<K, V> implements Entry<K, V>, Serializable {
        //JVM是根据SerialVersionUID来判断一个类的版本, 它可以显示声明也可以隐式声明,这里是显示声明
        //目的是在（远程）传输对象信息时避免因为双端版本不一致导致反序列化失败的情况
        @Serial
        private static final long serialVersionUID = -8499721149061103585L;
        // key被final修饰, 其引用一旦初始化便不再改变（这里在构造函数中初始化）；value可变
        private final K key;
        private V value;

        public SimpleEntry(K key, V value){
            this.key = key;
            this.value = value;
        }

        public SimpleEntry(Entry<? extends K, ? extends V> entry){
            this.key = entry.getKey();
            this.value = entry.getValue();
        }

        @Override
        public K getKey() {
            return key;
        }
        @Override
        public V getValue() {
            return value;
        }
        @Override
        public V setValue(V value) {
            V oldValue = this.value;
            this.value = value;
            return oldValue;
        }

        @Override
        public boolean equals(Object o){
            return o instanceof Map.Entry<?, ?> e
                    && Objects.equals(key, e.getKey())
                    && Objects.equals(value, e.getValue());
        }

        @Override
        public int hashCode(){
            return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode());
        }

        @Override
        public String toString(){return key + "=" + value;}
    }

    /**
     * 此Entry一经初始化, K-V均不允许修改, 不支持setValue方法
     * 类的实例不与任何Map的Entry-Set相关联
     */
    public static class SimpleImmutableEntry<K, V> implements Entry<K, V>, Serializable{
        @Serial
        private static final long serialVersionUID = 7138329143949025153L;

        private final K key;
        private final V value;

        public SimpleImmutableEntry(K key, V value) {
            this.key = key;
            this.value = value;
        }

        public SimpleImmutableEntry(Entry<? extends K, ? extends V> entry) {
            this.key = entry.getKey();
            this.value = entry.getValue();
        }

        @Override
        public K getKey() {
            return key;
        }

        @Override
        public V getValue() {
            return value;
        }

        @Override
        public V setValue(V value) {
            throw new UnsupportedOperationException();
        }

        @Override
        public boolean equals(Object o){
            return o instanceof Map.Entry<?, ?> e
                    && Objects.equals(key, e.getKey())
                    && Objects.equals(value, e.getValue());
        }

        @Override
        public int hashCode(){
            return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode());
        }

        @Override
        public String toString(){return key + "=" + value;}
    }


}
